package org.jeecg.modules.weixin.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;

@Slf4j
@Service
public class SubscribeMessageService {
    @Value("${weixin.appId}")
    String _appId = "";

    @Value("${weixin.secret}")
    String _secret = "";

    CloseableHttpClient httpClient = HttpClients.createDefault();

    @SneakyThrows
    public void send(String touser, String template_id, ObjectNode data) {
        String ACCESS_TOKEN = getAccessToken();
        if(ACCESS_TOKEN == null)
            return;

        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + ACCESS_TOKEN);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type","application/json; charset=utf-8");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();

        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("access_token", ACCESS_TOKEN)
                .put("touser", touser)
                .put("template_id", template_id)
                .put("data", data);

        objectMapper.writeValue(bos, rootNode);

        httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
        CloseableHttpResponse response = httpClient.execute(httpPost);

        String bodyAsString = EntityUtils.toString(response.getEntity());
        log.info("subscribe 返回, {}", bodyAsString);

    }

    @SneakyThrows
    private String getAccessToken() {
        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + _appId + "&secret=" + _secret);
        CloseableHttpResponse response =  httpClient.execute(httpGet);
        String bodyAsString = EntityUtils.toString(response.getEntity());
        log.info(bodyAsString);
        if(bodyAsString != null) {
            JSONObject jsonObject = JSONObject.parseObject(bodyAsString);
            return jsonObject.getString("access_token");
        }

        return null;
    }
}
